package com.example.demo.controller;

import com.example.demo.commom.AjaxResult;
import com.example.demo.commom.TimeForMat;
import com.example.demo.commom.UserSessionUtils;
import com.example.demo.entity.Articleinfo;
import com.example.demo.entity.Userinfo;
import com.example.demo.service.ArticleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User:龙宝
 * Date:2023-04-02
 * Time:21:10
 */
@RestController
@RequestMapping("/art")
public class ArticleController {
    @Autowired
    private ArticleService articleService;

    @RequestMapping("mylist")
    public AjaxResult myList(Integer state,HttpServletRequest request) {
        Userinfo userinfo = UserSessionUtils.getUser(request);
        if(userinfo == null) {
            return AjaxResult.fail("未登录",-2);
        }
        List<Articleinfo> lists = articleService.getMyList(userinfo.getId(),state);
        return AjaxResult.success(lists);
    }

    @RequestMapping("del")
    public AjaxResult del(Integer id,HttpServletRequest request) {
        if(id == null || id <=0) {
            return AjaxResult.fail("参数有误",-1);
        }
        Userinfo userinfo = UserSessionUtils.getUser(request);
        if(userinfo == null) {
            return AjaxResult.fail("参数有误",-1);
        }
        int ret = articleService.del(userinfo.getId(), id);
        return AjaxResult.success(ret);

    }

    @RequestMapping("/detail")
    public AjaxResult getDetail(Integer id) {
        if(id == null || id<=0) {
            return AjaxResult.fail("非法参数",-1);
        }
        return AjaxResult.success(articleService.getDetail(id));
    }
    @RequestMapping("/uprcount")
    public AjaxResult upRCount(Integer id) {
        //验证参数是否有效
        if(id == null || id<=0) {
            return AjaxResult.fail("参数错误",-1);
        }
        //增加阅读量的值
        return AjaxResult.success(articleService.upRCount(id));
    }
    //添加博客
    @RequestMapping("/add")
    public AjaxResult add(Articleinfo articleinfo,HttpServletRequest request) {
        if(articleinfo == null || !StringUtils.hasLength(articleinfo.getTitle())
        ||!StringUtils.hasLength(articleinfo.getContent())) {
            //非空校验
            return AjaxResult.fail("参数有误",-1);
        }

        Userinfo userinfo = UserSessionUtils.getUser(request);
        if(userinfo == null || userinfo.getId()<=0) {
            return AjaxResult.fail("请登录后操作",-1);
        }
        articleinfo.setUid(userinfo.getId());

        if(articleinfo.getId() == null) {
            return AjaxResult.success(articleService.add(articleinfo));
        } else if(articleinfo.getId() < 0) {
            //非空校验
            return AjaxResult.fail("参数有误",-1);
        }else {
            articleinfo.setState(1);
            return AjaxResult.success(articleService.edit(articleinfo));
        }
    }
    @RequestMapping("/edit")
    public AjaxResult edit(Articleinfo articleinfo,HttpServletRequest request) {
        if(articleinfo == null || !StringUtils.hasLength(articleinfo.getTitle())
                ||!StringUtils.hasLength(articleinfo.getContent())) {
            //非空校验
            return AjaxResult.fail("参数有误",-1);
        }

        int ret = articleService.edit(articleinfo);
        return AjaxResult.success(ret);
    }

    /**
     * 分页查询
     * @param psize 每页显示条数
     * @param index 当前页码
     * @return
     */
    @RequestMapping("/listpage")
    public AjaxResult listPage(Integer index,Integer psize) {
        //参数矫正
        if(psize == null || psize < 1) {
            psize = 1;
        }
        if(index == null ||index < 1) {
            index = 1;
        }
        //根据当前页码得到偏移量
        int offset = (index-1) * psize;
        System.out.println(psize);
        System.out.println(offset);
        List<Articleinfo> list = articleService.listPage(psize,offset);

        //此时需要返回的数据的已经准备好了，但我们另外还需要返回末页的页码数，为跳转到末页做准备
        int artCount = articleService.artCount();
        int sizeLast = 0;
        if(artCount % psize == 0) {
            sizeLast = artCount/psize;
        } else {
            sizeLast = artCount/psize + 1;
        }
        HashMap<String,Object> map = new HashMap<>();
        map.put("list",list);
        map.put("sizeLast",sizeLast);
        return AjaxResult.success(map);
    }

    /**
     * 保存草稿
     * @param articleinfo
     * @param request
     * @return
     */
    @RequestMapping("/draft")
    public AjaxResult myDraft(Articleinfo articleinfo,HttpServletRequest request) {
        //1、判空
        if(articleinfo == null || !StringUtils.hasLength(articleinfo.getTitle())) {
            return AjaxResult.fail("参数有误",-1);
        }
        //获取当前用户身份
        Userinfo userinfo = UserSessionUtils.getUser(request);
        //草稿时，设置state为0，发布时设置为1
        //因此，之前的功能也需要稍做调整【查询时】
        if(userinfo == null || userinfo.getId()<=0) {
            return AjaxResult.fail("请登录后操作",-1);
        }
        articleinfo.setUid(userinfo.getId());
        articleinfo.setState(0);
        if(articleinfo.getId() == null) {
            int ret = articleService.myDraft(articleinfo);
            //新草稿 给前端返回id信息
            //查询
            HashMap<Object,Integer> map = new HashMap<>();
            map.put("ret",ret);
            map.put("id", -1);
            return AjaxResult.success(map);

        }
        //旧文章草稿，不用搜索文章id信息
        int ret = articleService.edit(articleinfo);
        HashMap<Object,Integer> map = new HashMap<>();
        map.put("ret",ret);
        map.put("id",articleinfo.getId());
        return AjaxResult.success(map);
    }

    /**
     * 定时发布
     * @param day 天
     * @param time 时间
     * @return
     */
    //todo:线程安全问题
    @RequestMapping("/mytiming")
    public AjaxResult myTiming(String day,String time,Articleinfo articleinfo,HttpServletRequest request) {

        //1、时间处理
        if(!StringUtils.hasLength(day) || !StringUtils.hasLength(time)) {
            return AjaxResult.fail("参数异常",-1);
        }
        if(articleinfo == null || !StringUtils.hasLength(articleinfo.getTitle())
                ||!StringUtils.hasLength(articleinfo.getContent())) {
            //非空校验
            return AjaxResult.fail("参数有误",-1);
        }
        //指定时间
        String assignTime = day +" "+time+":00";//2023-04-05 20:32
        //时间格式转换--指定的时间戳
        Long assTime = TimeForMat.timeFormat(assignTime);
        //获取当前时间戳
        Long nowTime = System.currentTimeMillis();
        //比较时间
        Long lastTime = 0L;
        if(nowTime < assTime) {
            lastTime = assTime-nowTime;
        }

        //2、用户身份
        Userinfo userinfo = UserSessionUtils.getUser(request);
        if(userinfo == null || userinfo.getId()<=0) {
            return AjaxResult.fail("参数有误",-1);
        }
        //文章uid
        articleinfo.setUid(userinfo.getId());

        //3、定时器---多线程
//        ExecutorService pool = Executors.newCachedThreadPool();
        Long finalLastTime = lastTime;
        //d对id是否有效验证
        if(articleinfo.getId() != null && articleinfo.getId() < 0) {
            return AjaxResult.fail("参数有误",-1);
        }

//        pool.submit(new Runnable() {
//            @Override
//            public void run() {
                Timer timer = new Timer();
                timer.schedule(new TimerTask() {
                    @Override
                    public void run() {
                        System.out.println("时间到，发布博客");
                        if(articleinfo.getId() == null) {
                            AjaxResult.success(articleService.add(articleinfo));
                        } else {
                            articleinfo.setState(1);
                            AjaxResult.success(articleService.edit(articleinfo));
                        }
                    }
                }, finalLastTime);
//            }
//        });

        return AjaxResult.success(1);
    }
}
